package com
{
	import com.assist.data.IData;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;

	public class DataBase implements IData
	{
		protected var _ctrl :Controller;
		protected var _view :View;
		protected var _sock :Socket;
		protected var _onConnect :Function;
		
		private var _host :String;
		private var _port :uint;
		private var _connectSucceed :Boolean = false;
		
		public function DataBase()
		{
			_sock = new Socket();
		}
		
		public function init( view :View, ctrl :Controller ) :void {
			_view = view;
			_ctrl = ctrl;
		}
		
		public function connect( host :String, port :uint ) :void {
			_host = host;
			_port = port;
			
			addListener();
			
			if( _sock.connected ) {
				_sock.close();
			}
			_sock.connect( _host, _port );
		}
		
		public function set onConnect( func :Function ) :void {
			_onConnect = func;
		}
		
		public function call(param1:Object, param2:Function, param3:Array, param4:Boolean = true) : void {
			
		}
		
		public function patch(param1:Object, param2:Function) : void {
			
		}
		
		public function cancelPatch(param1:Object) : void {
			
		}
		
		public function close() : void {
			
		}
		
		public function set onClose(param1:Function) : void {
			
		}
		
		private function addListener() :void {
			_sock.addEventListener(Event.CONNECT, onConnectHandler);
			_sock.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorHandler);
			_sock.addEventListener(ProgressEvent.SOCKET_DATA, onSocketDataHandler);
			_sock.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorHandler);
			_sock.addEventListener(Event.CLOSE, onCloseHandler);
		}
		
		private function removeListener() :void {
			_sock.removeEventListener(Event.CONNECT, onConnectHandler);
			_sock.removeEventListener(IOErrorEvent.IO_ERROR, onIOErrorHandler);
			_sock.removeEventListener(ProgressEvent.SOCKET_DATA, onSocketDataHandler);
			_sock.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorHandler);
			_sock.removeEventListener(Event.CLOSE, onCloseHandler);
		}
		
		private function onConnectHandler( event :Event ) :void {
			trace("Connect Success");
			onConnectHandlerReal();
		}
		
		private function onConnectHandlerReal() :void {
			_connectSucceed = true;
			if( _onConnect is Function ) {
				_onConnect();
				_onConnect = null;
			}
		}
		
		private function onIOErrorHandler( event :IOErrorEvent ) :void {
			trace("IOError");
			//for test
			onConnectHandlerReal();
		}
		
		private function onSocketDataHandler( event :ProgressEvent ) :void {
			
		}
		
		private function onSecurityErrorHandler( event :SecurityErrorEvent ) :void {
			
		}
		
		private function onCloseHandler( event :Event ) :void {
			trace("Close");
		}
	}
}